package com.gxjtkyy.datadistributer.writer.rdbms.service;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.stereotype.Service;

@Service
public class MetricService {
   private static final ConcurrentMap<String, Counter> OK_COUNTER_MAP = new ConcurrentHashMap();
   private static final ConcurrentMap<String, Counter> ERROR_COUNTER_MAP = new ConcurrentHashMap();
   private final MeterRegistry registry;

   public void countSendToKafkaOk(String topic, long count) {
      Counter okCounter = this.getOkCounter(topic);
      okCounter.increment((double)count);
   }

   public void countSendToKafkaError(String topic, long count) {
      Counter errorCounter = this.getErrorCounter(topic);
      errorCounter.increment((double)count);
   }

   private Counter getOkCounter(String topic) {
      Counter counter = (Counter)OK_COUNTER_MAP.get(topic);
      if (counter != null) {
         return counter;
      } else {
         synchronized(OK_COUNTER_MAP) {
            counter = (Counter)OK_COUNTER_MAP.get(topic);
            if (counter != null) {
               return counter;
            } else {
               counter = Counter.builder("distribute.records").tag("source", "queue").tag("destination", "db").tag("name", topic).tag("status", "ok").register(this.registry);
               OK_COUNTER_MAP.put(topic, counter);
               return counter;
            }
         }
      }
   }

   private Counter getErrorCounter(String topic) {
      Counter counter = (Counter)ERROR_COUNTER_MAP.get(topic);
      if (counter != null) {
         return counter;
      } else {
         synchronized(ERROR_COUNTER_MAP) {
            counter = (Counter)ERROR_COUNTER_MAP.get(topic);
            if (counter != null) {
               return counter;
            } else {
               counter = Counter.builder("distribute.records").tag("source", "queue").tag("destination", "db").tag("name", topic).tag("status", "error").register(this.registry);
               ERROR_COUNTER_MAP.put(topic, counter);
               return counter;
            }
         }
      }
   }

   public MetricService(final MeterRegistry registry) {
      this.registry = registry;
   }
}
